$(function(){
    // 用户添加模块
    $("#add-user").click(function(){
        $("input").val("");
        $('#edit').val('false');
        $.ajax({
            url: '/admin-role-all',
            type: 'get',
            success: function(data){
                let html = ``;
                for (let i = 0; i < data.length; i++) {
                    html += `<div class="checkbox" style="margin: 0px;">
                                <label>
                                    <input type="checkbox" name="role" value="`+data[i].id+`">`+data[i].role_name+`
                                </label>
                            </div>`;
                }
                $('#user-set-role').html(html);
                layer.open({
                    type: 1,
                    title: '添加用户',
                    area: ['80vw', '80vh'],
                    content: $("#user-form-content")
                });
            }
        })

    });
    $("#user-submit").click(function(){
        let username = $('#name').val();
        let mobile = $('#mobile').val();
        let email = $('#email').val();
        let birthday = $('#date').val();
        let password = $('#password').val();
        let edit = $('#edit').val();
        let id = $('#id').val();
        let role_ids = [];
        $('input[name="role"]:checked').each(function(){
            role_ids.push($(this).val());
        });
        if (edit == 'true') {
            $.ajax({
                url: '/admin-user-edit',
                type: 'post',
                data: {id:id, username:username, email:email, mobile:mobile, birthday:birthday, password:password, role_ids:role_ids},
                success: function(data){
                    if(!data.status || data.code==0){
                        layer.msg(data.msg, {
                            icon: 5
                        });
                        return;
                    }
                    layer.msg(data.msg);
                    $('#user').bootstrapTable('refresh', {url: '/admin-user-infos'});
                }
            })
        }else{
            $.ajax({
                url: '/admin-user-add',
                type: 'post',
                data: {username:username, email:email, mobile:mobile, birthday:birthday, password:password, role_ids:role_ids},
                success: function(data){
                    if(!data.status || data.code==0){
                        layer.msg(data.msg, {
                            icon: 5
                        });
                        return;
                    }
                    layer.msg(data.msg);
                    $('#user').bootstrapTable('refresh', {url: '/admin-user-infos'});
                }
            })
        }
    })

    // 用户信息验证模块
    jQuery.validator.addMethod("isMobile", function(value, element) {
        var length = value.length;
        var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
        return this.optional(element) || (length == 11 && mobile.test(value));
    }, "请正确填写手机号码");
    $('#userForm').validate({
        rules: {
            name: {
                required: true,
                minlength: 2
            },
            mobile: {
                isMobile: true,
                required: true,
                digits: true,
                minlength: 11
            },
            email: {
                email: true,
                required: true
            },
            date: {
                date: true,
                required: true
            },
            password: {
                required: true,
                minlength: 6
            },
            confirm_password: {
                required: true,
                minlength: 6,
                equalTo: '#password'
            }
        },
        messages: {
            name: {
                required: '请输入你的用户名',
                minlength: '用户名必须大于两位'
            },
            mobile: {
                isMobile: '请输入正确手机号',
                required: '请输入你的手机号',
                digits: '请输入正确手机号',
                minlength: '手机号必须是11位以上'
            },
            email: {
                email: '请输入有效的邮箱地址',
                required: '请输入你的邮箱'
            },
            date: {
                date: '请输入有效日期格式',
                required: '请输入你的生日'
            },
            password: {
                required: '请输入密码',
                minlength: '密码长度必须大于6位'
            },
            confirm_password: {
                required: '请确认密码',
                minlength: '密码长度必须大于6位',
                equalTo: '两次输入密码不一致'
            }
        }
    });

    // 用户信息列表模块
    window.operateEvents = {
        "click #editRow":function(e, value, row, index){
            $('input').val('');
            $('#name').val(row.username);
            $('#email').val(row.email);
            $('#mobile').val(row.mobile);
            $('#date').val(row.birthday);
            $('#id').val(row.id);
            $('#edit').val('true');

            $.ajax({
                url: '/admin-role-all-edit',
                type: 'post',
                data:{id:row.id},
                success: function(data){
                    let html = ``;
                    for (let i = 0; i < data.length; i++) {
                        if (data[i].selected) {
                            html += `<div class="checkbox" style="margin: 0px;">
                                <label>
                                    <input type="checkbox" name="role" value="`+data[i].id+`" checked>`+data[i].role_name+`
                                </label>
                            </div>`;
                        }else{
                            html += `<div class="checkbox" style="margin: 0px;">
                                <label>
                                    <input type="checkbox" name="role" value="`+data[i].id+`">`+data[i].role_name+`
                                </label>
                            </div>`;
                        }
                    }
                    $('#user-set-role').html(html);
                    layer.open({
                        type: 1,
                        title: '<b>编辑用户</b>--'+row.username,
                        area: ['80vw', '80vh'],
                        content: $("#user-form-content")
                    });
                }
            })
        },
        "click #deleteRow":function(e, value, row, index){
            $.ajax({
                url: '/admin-user-delete',
                type: 'post',
                data: {id:row.id},
                success: function(data){
                    if(!data.status || data.code==0){
                        layer.msg(data.msg, {
                            icon: 5
                        });
                        return;
                    }
                    layer.msg(data.msg);
                    $('#user').bootstrapTable('refresh', {url: '/admin-user-infos'});
                }
            })
        },
    }
    $("#user").bootstrapTable({
        url:"/admin-user-infos",
        columns:[
            {
                field:"select",
                title:"全选",
                checkbox:true
            },
            {
                field:'id',
                title:'id',
                visible: false
            },
            {
                field:'username',
                title:'用户名'
            },
            {
                field:'email',
                title:'邮箱'
            },
            {
                field:'mobile',
                title:'手机'
            },
            {
                field:'birthday',
                title:'生日'
            },
            {
                field:'updater',
                title:'更新人'
            },
            {
                field:'update_time',
                title:'更新时间'
            },
            {
                field:'Button',
                title:'操作',
                events:operateEvents,
                formatter:addButtons,
            },
        ],
        striped:true,
        sortName:'id',                    // 排序字段名
        sortOrder:'asc',                   // 升降序，默认升序
        icons:{
            paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
            refresh: 'glyphicon-refresh icon-refresh',
            toggle: 'glyphicon-list-alt icon-list-alt',
            columns: 'glyphicon-th icon-th',
            detailOpen: 'glyphicon-plus icon-plus',
            detailClose: 'glyphicon-minus icon-minus',
        },
        pagination:true,                    // 分页
        onlyInfoPagination:false,           // 只显示数据量
        pageSize:10,                         // 每页数据量
        pageList:[10,20,30,50],                   // 可选择每页数据量
        search:false,                        // 显示搜索
        selectItemName:'id',
        showHeader:true,                    // 显示头
        showColumns:true,                   // 显示列下拉框
        showRefresh:true,                   // 显示刷新
        showToggle:true,                    // 切换试图
        showPaginationSwitch:true,          // 显示分页切换按钮
        idField:'id',                       // 指定主键
        uniqueId:'id',                      // 设置每一行唯一标识符
        detailView:false,                    // 显示详细页面
        searchAlign:'left',                // 搜索框位置
        buttonsAlign:'right',                 // 按钮位置
        paginationVAlign:'bottom',
        paginationHAlign:'right',
        paginationPreText:'上一页',
        paginationNextText:'下一页',
        toolbar:'#toolbar',
        toolbarAlign:'left',
        sidePagination:'server',            // 客户端还是服务端分页
        queryParams: function queryParams(params) {
            return {
                pageNumber: params.offset,
                pageSize: params.limit,
                name:$("#search_name").val(),
                email:$("#search_email").val()
            };
        },
    });
    $('#search_btn').click(function(){
        $('#user').bootstrapTable('refresh', {url: '/admin-user-infos'});
    });
    function addButtons(){
        return [
            "<button type='button' id='editRow' class='btn btn-success btn-xs'>编辑</button>&nbsp;&nbsp;",
            "<button type='button' id='deleteRow' class='btn btn-danger btn-xs'>删除</button>",
        ].join("")
    }
})
